<template>
  <div class="container">
    <div class="content">
      <el-date-picker
          v-model="date"
          type="date"
          placeholder="请选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="historyData"
      />
      <div class="date-list">
        <div class="date-item" v-for="(item, index) in dateList" :key="index">
          <div class="item-text" @click="selectDateRange(item)">
            <el-icon style="vertical-align: middle"><VideoCamera /></el-icon>
            {{item.startTime + '-' + item.endTime}}
          </div>
          <div class="item-icon" @click="downloadVideoData(item)">
            <el-icon><Download /></el-icon>
          </div>
        </div>
      </div>
    </div>
    <div class="content content-right">
      <div class="video">
        <video ref="videoRef" style="width: 100%; height: 100%" controls :autoplay="false" poster="@/assets/images/oceans.png" muted @timeupdate="selectVideoTime">
          <source :src="videoSrc" type="video/mp4">
          Your browser does not support the video tag.
        </video>
      </div>
      <div style="margin-top: 10px; text-align: center">
        <el-time-picker
            style="vertical-align: middle"
            v-model="dataRange"
            is-range
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            size="small"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            @change="changeTime"
        />
        <el-radio-group v-model="videoStauts" size="small" style="vertical-align: middle; margin-left: 10px" @change="changeRadio">
          <el-radio-button label="pause">‖</el-radio-button>
          <el-radio-button label="play">▶</el-radio-button>
          <el-radio-button label="download">↓</el-radio-button>
          <el-radio-button label="speed">倍速</el-radio-button>
        </el-radio-group>
      </div>
      <!-- <div class="slider">
        <el-slider v-model="sliderValue" :max="sliderMax" range :format-tooltip="formatTooltip" @change="changeSlider" :marks="marks"/>
      </div> -->
    </div>
  </div>
</template>

<script setup>
import {nextTick, onBeforeUnmount, onMounted, reactive, ref} from "vue";
import { useRoute } from "vue-router";
import {historyApi, startHistory, stopHistory} from "@/api/monitoring/monitoring";
import moment from "moment";

const { proxy } = getCurrentInstance();
const route = useRoute();
const queryForm = ref({
  deviceId: null,
  channelId: null
})
const date = ref('')
const sliderValue = ref([0, 3600])
const sliderMax = ref(86399)
const dataRange = ref(['00:00:00', '01:00:00'])
const videoStauts = ref('play')
const dateList = ref([])
const recordList = ref([])
const videoSrc = ref('')
const videoRef = ref(null)
const startTime = ref('')
const endTime = ref('')
let thisPlayer = null;
const marks = reactive({})

onMounted(() => {
  date.value = moment().format('YYYY-MM-DD')
  queryForm.value = Object.assign(route.query)
  initMarks()
  historyData();
})

onBeforeUnmount(() => {
  stop()
});


const initMarks = () => {
  for(let i = 0; i <= 24; i++) {
    if (i === 24) {
      marks[86399] = '24:00'
      return
    }
    marks[ i * 3600] = i <= 9 ? `0${i}:00` : `${i}:00`
  }
}

// 发送请求
const historyData = () => {
  const deviceId = queryForm.value.deviceId;
  const channelId = queryForm.value.channelId ? queryForm.value.channelId : '34020000001310000001'
  const startTime = date.value + ' 00:00:00'
  const endTime = date.value + ' 23:59:59'
  historyApi(deviceId, channelId, startTime, endTime).then(res => {
    const { code, data } = res;
    if (code === 200) {
      recordList.value = data['recordList']
      data['recordList'].forEach( item => {
        dateList.value.push({
          startTime: item.startTime.slice(11),
          endTime: item.endTime.slice(11)
        })
      })
      // 默认播放第一个
      // videoSrc.value = data['recordList'][0].filePath
      // videoRef.value.src(data['recordList'][0].filePath)
      // //videoSrc.value = 'https://cloud.video.taobao.com/play/u/29571933/p/1/d/ld/e/6/t/1/477015547474.mp4?auth_key=YXBwX2tleT04MDAwMDAwMTImYXV0aF9pbmZvPXsidGltZXN0YW1wRW5jcnlwdGVkIjoiMzlhODc4OTU4YzU4Yzk1MmUzNWNlMThmNDBkOTcyYzgifSZkdXJhdGlvbj0mdGltZXN0YW1wPTE3MjQwNzM3NTM='
      // nextTick(() => {
      //   videoRef.value.load()
      // })
      // setTimeout(() => {
      //   sliderMax.value = Math.floor(videoRef.value.duration)
      // }, 100)
    }
  })
}

/**
 * 播放回放视频
 * @param startTime
 * @param endTime
 */
const startPlayer = (startTime,endTime) => {
  stop();
  startHistory(queryForm.value.deviceId, queryForm.value.channelId, date.value+" "+startTime, date.value+" "+endTime).then(res => {
    let data = res.data;
    thisPlayer = data;
    videoSrc.value = data.fmp4.replace("%20","_").replace("%20","_");
	console.log(videoSrc.value+"/n"+data.fmp4)
    //videoRef.value.src(data.fmp4)
    //videoSrc.value = 'https://cloud.video.taobao.com/play/u/29571933/p/1/d/ld/e/6/t/1/477015547474.mp4?auth_key=YXBwX2tleT04MDAwMDAwMTImYXV0aF9pbmZvPXsidGltZXN0YW1wRW5jcnlwdGVkIjoiMzlhODc4OTU4YzU4Yzk1MmUzNWNlMThmNDBkOTcyYzgifSZkdXJhdGlvbj0mdGltZXN0YW1wPTE3MjQwNzM3NTM='
    nextTick(() => {
      videoRef.value.load()
	  setTimeout(()=>{
	  	videoRef.value.play()
	  },5*1000)
    })
    setTimeout(() => {
      sliderMax.value = Math.floor(videoRef.value.duration)
    }, 100)
  })
}

/**
 * 停止回放视频
 */
const stop = ()=>{
  if(!thisPlayer){
    return
  }
  stopHistory(queryForm.value.deviceId, queryForm.value.channelId, thisPlayer.stream).then(res => {
    console.log(res)
  })
}

// 切换时间范围并且切换视频
const selectDateRange = (value) => {
	proxy.$modal.msgSuccess("视频加载中..");
  startPlayer(value.startTime, value.endTime)
  // const currentVideo = getCurrentVideo(value);
  // videoSrc.value = currentVideo.filePath
  // videoRef.value.src(currentVideo.filePath)
  // nextTick(() => {
  //   videoRef.value.load()
  // })
  // setTimeout(() => {
  //   sliderMax.value = Math.floor(videoRef.value.duration)
  // }, 100)
}

// 下载视频
const downloadVideoData = (value) => {
  const currentVideo = getCurrentVideo(value)
  if (currentVideo.filePath) {
    getVideo(currentVideo.filePath)
  }
}

// 获取当前视频
const getCurrentVideo = (value) => {
  return recordList.value.filter(item => {
    return item.startTime.slice(11) === value.startTime && item.endTime.slice(11) === value.endTime
  })
}

// 操作视频
const changeRadio = () => {
  switch (videoStauts.value) {
    case 'pause':
      pauseVideo()
      break;
    case 'play':
      playVideo();
      break;
    case 'download':
      downloadVideo();
      break;
    case 'speed':
      speedVideo();
      break;
  }
}

// 暂停视频
const pauseVideo = () => {
  proxy.$modal.msgSuccess("视频暂停");
  console.log('暂停视频')
  videoRef.value.pause()
}
// 播放视频
const playVideo = () => {
	proxy.$modal.msgSuccess("视频播放");
  console.log('播放视频')
  videoRef.value.playbackRate = 1
  videoRef.value.play()
	setTimeout(()=>{
		videoRef.value.play()
	},666)
}
// 下载视频
const downloadVideo = () => {
  console.log('下载视频')
  getVideo(videoRef.value.currentSrc)
}
// 倍速视频
const speedVideo = () => {
	proxy.$modal.msgSuccess("视频开始倍速");
  console.log('倍速视频')
  videoRef.value.playbackRate = 2
}
// 下载视频文件
const getVideo = (url) => {
	proxy.$modal.msgSuccess("开始下载视频文件");
  var name = "视频";//下载的文件名
  fetch(url)
      .then(res => res.blob())
      .then(blob => {
        const a = document.createElement("a");
        const objectUrl = window.URL.createObjectURL(blob);
        a.download = name;
        a.href = objectUrl;
        a.click();
      })
}
// 滑块
const changeSlider = () => {
  // videoRef.value.currentTime = sliderValue.value
  // let time=moment.duration('24:00:00').as('seconds')
  // console.log(time)
  // console.log(111, moment.utc(3600 * 1000).format('HH:mm:ss'))
  console.log(sliderValue.value)
  startTime.value = moment.utc(sliderValue.value[0] * 1000).format('HH:mm:ss')
  endTime.value = moment.utc(sliderValue.value[1] * 1000).format('HH:mm:ss')
  dataRange.value[0] = startTime.value
  dataRange.value[1] = endTime.value
  startPlayer(startTime.value, endTime.value)
}
const formatTooltip = (val) => {
  return moment.utc(val * 1000).format('HH:mm:ss')
}
const changeTime = () => {
	console.log(dataRange.value)
  startTime.value = dataRange.value[0]
  endTime.value = dataRange.value[1]
  proxy.$modal.msgSuccess("视频重新加载中...");
  // sliderValue.value[0] = moment.duration(dataRange.value[0]).asSeconds();
  // sliderValue.value[1] = moment.duration(dataRange.value[1]).asSeconds();
  startPlayer(startTime.value, endTime.value)
}
// 点击视频进度条
const selectVideoTime = (value) => {
  //sliderValue.value = Math.floor(videoRef.value.currentTime)
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: calc(100vh - 84px);
  display: flex;
  background: #F0F0F0;
  .content {
    padding: 10px;
    .date-list {
      margin-top: 10px;
      background: #fff;
      padding: 10px;
      border-radius: 5px;
      width: 100%;
      font-size: 14px;
      overflow: auto;
      .date-item {
        width: 200px;
        display: flex;
        align-items: center;
        margin-top: 3px;
        padding: 5px;
        color: rgb(130, 191, 255);
        .item-text {
          width: 160px;
          background: rgb(236, 245, 255);
          border: 1px solid rgb(224, 239, 255);
          border-radius: 5px;
          padding: 5px;
          cursor:pointer;
        }
        .item-icon {
          flex: 1;
          margin-left: 10px;
        }
      }
    }
    .video {
      width: 100%;
      height: calc(100vh - 200px);
    }
  }
  .content-right {
    flex: 1;
    padding: 10px;
    .slider {
      padding: 0 20px;
    }
  }

  /* 为了兼容其他浏览器，可以添加以下样式 */
  video {
    controls: none !important;
  }

  //全屏按钮
  video::-webkit-media-controls-fullscreen-button {
    display: none;
  }
  //播放按钮
  video::-webkit-media-controls-play-button {
    display: none;
  }
  //进度条
  video::-webkit-media-controls-timeline {
    display: none;
  }
  //观看的当前时间
  video::-webkit-media-controls-current-time-display{
    display: none;
  }
  //剩余时间
  video::-webkit-media-controls-time-remaining-display {
    display: none;
  }
  //音量按钮
  video::-webkit-media-controls-mute-button {
    display: none;
  }
  video::-webkit-media-controls-toggle-closed-captions-button {
    display: none;
  }
  //音量的控制条
  video::-webkit-media-controls-volume-slider {
    display: none;
  }
  //所有控件
  video::-webkit-media-controls-enclosure{
    display: none;
  }
}
</style>
